/* 
 * File:   main.cpp
 * Author: Dann
 *
 * Created on June 2, 2013, 1:55 AM
 */

#include <cstdlib>
#include "fileutils.h"
#include "fileinfo.h"
#include <iostream>
#include <iomanip> 

using namespace std;

#define COLUMNS_COUNT 6

enum ArgsErrorCode
{
    WRONG_PARAMETERS = -1, NORMAL = 0, LONG_FORMAT = 1
};

ArgsErrorCode validatePath(const char* path)
{

}

bool validateCommand(const char* path)
{
    return path[0] == '-' && path[1] == 'l';
}

ArgsErrorCode validateParameters(int argCount, char** args)
{
    switch (argCount)
    {
    case 2:
        if (exist(args[1]))
        {
            return NORMAL;
        }

        return WRONG_PARAMETERS;
        break;
    case 3:
        if (validateCommand(args[1]))
        {
            if (exist(args[2]))
            {
                return LONG_FORMAT;
            }
        }
    default: return WRONG_PARAMETERS;
    }
}

void normalList(const char* path)
{
    std::list<std::string> files = listFiles(path);
    std::list<std::string>::const_iterator it = files.begin();
    std::cout << std::left;
    int count = COLUMNS_COUNT;

    while (it != files.end())
    {

        std::string test = *it;
        std::cout << std::setw(20) << test;
        it++;
        count--;

        if (count == 0)
        {
            count = COLUMNS_COUNT;
            std::cout << std::endl;
        }
    }

    std::cout << std::endl;
}

void longList(const char* path)
{
    std::list<std::string> files = listFiles(path);

    std::cout << std::left;
    std::cout << "total " << files.size() << std::endl;
    
    for (std::list<std::string>::const_iterator it = files.begin(); it != files.end(); it++)
    {
        std::string file = *it;
        FileInfo fileInfo(path, file);
        std::cout << std::setw(11) << fileInfo.getPermissions();
        std::cout << std::setw(10) << fileInfo.getOwner();
        std::cout << std::setw(10) << fileInfo.getGroup();
        std::cout << std::setw(10) << fileInfo.getSize();
        std::cout << std::setw(26) << fileInfo.getLastModificationTime();
        std::cout << std::setw(26) << fileInfo.getLastAccessTime();
        std::cout << std::setw(15) << fileInfo.getName();
        std::cout << std::endl;
    }
}

/*
 * 
 */
int main(int argc, char** argv)
{
    switch (validateParameters(argc, argv))
    {
    case WRONG_PARAMETERS: std::cout << "Check the parameters.\n";
        break;
    case NORMAL: normalList(argv[1]);
        break;
    case LONG_FORMAT: longList(argv[2]);
        break;
    }
    return 0;
}

